package com.zhihesj.anan.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhihesj.anan.system.entity.Role;
import com.zhihesj.anan.system.entity.User;
import com.zhihesj.anan.system.entity.UserAuths;
import com.zhihesj.anan.system.service.RoleService;
import com.zhihesj.anan.system.service.UserAuthsService;
import com.zhihesj.anan.system.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 */
@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserAuthsService userAuthsService;

    /**
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("JwtUserDetailsService:" + username);
        QueryWrapper<UserAuths> wrapper = new QueryWrapper<>();
        wrapper.eq("identifier", username);
        UserAuths userAuths = userAuthsService.getOne(wrapper);
        if (userAuths == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        return new SecurityUserDetails(userAuths.getIdentifier(), userAuths.getCredential(), getGrantedAuthority(userAuths));
    }

    public List<GrantedAuthority> getGrantedAuthority(User user){
        List<GrantedAuthority> list = new ArrayList<>();
        List<Role> roles=userService.getRolesById(user.getId());
        if (roles.size() > 0) {
            for (Role role:roles) {
                list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleKey().toUpperCase()));
            }
        }
        return list;
    }

    public List<GrantedAuthority> getGrantedAuthority(UserAuths userAuths){
        List<GrantedAuthority> list = new ArrayList<>();
        List<Role> roles = roleService.getRolesByUserid(userAuths.getUserId());

        if (roles.size() > 0) {
            for (Role role:roles) {
                list.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleKey().toUpperCase()));
            }
        }
        return list;
    }
}
